package com.md.model.base;

import com.md.model.html.CustomLabel;
import com.md.model.word.Document;
import com.md.util.ObjectUtil;
import com.md.value.html.LabelAttributeType;
import com.md.value.html.Unit;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xwpf.usermodel.XWPFPictureData;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.picture.CTPicture;

import java.util.Optional;

/**
 * @author 刘骄阳
 * 2024-07-28 15:35
 */
@Slf4j
public class Picture extends CustomLabel {

  public Picture(final CTPicture picture,
                 final Document document) {
    super("img");
    FileStream fileStream = null;
    try {
      Optional<XWPFPictureData> optionalXWPFPictureData = document.getPictureData(picture);
      if (optionalXWPFPictureData.isPresent()) {
        XWPFPictureData xwpfPictureData = optionalXWPFPictureData.get();
        fileStream = new FileStream(xwpfPictureData);
      } else {
        String link = picture.getBlipFill().getBlip().getLink();
        String url = document.getXwpfDocument().getPackagePart().getRelationships()
          .getRelationshipByID(link).getTargetURI().toString();
        fileStream = new FileStream(url);
      }
      CTPositiveSize2D ext = picture.getSpPr().getXfrm().getExt();
      addAttribute(LabelAttributeType.WIDTH, ext.getCx(), Unit.EMU);
      addAttribute(LabelAttributeType.HEIGHT, ext.getCy(), Unit.EMU);
      addAttribute(LabelAttributeType.SRC, document.uploadFile(fileStream));
    } catch (Exception e) {
      log.error("初始化图片异常: {}", e.getMessage(), e);
    } finally {
      if (ObjectUtil.notEmpty(fileStream)) {
        fileStream.close();
      }
    }
  }
}
